package kzy.filter;

import com.alibaba.fastjson.JSON;
import kzy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author 大溪地
 * @create 2023年05月24日23:22
 */
@WebFilter
@Slf4j
public class LoginCheckFilter implements Filter {
	public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Filter.super.init(filterConfig);
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//	1	先强转为Http类型
		HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
		HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
//  2    获取url地址
		String requestURI = httpServletRequest.getRequestURI();
		log.info(requestURI);

//  3    设置不拦截的路径
		String[] urls=new String[]{
		"/backend/**",
		"/front/**",
		"/user/sendMsg",
		"/user/login",
		"/employee/login",
		"/employee/logout",
		"/captchaController"
		};
//	4	调用方法 查看路径是否放行
		boolean check = check(urls, requestURI);

		if(check){
//			直接放行
			log.info("check 直接放行");
			filterChain.doFilter(httpServletRequest, httpServletResponse);
			return;

		}

		if((httpServletRequest.getSession().getAttribute("employee")!=null)){
			//			直接放行
			log.info("登录啦 直接放行");
			filterChain.doFilter(httpServletRequest, httpServletResponse);
			return;
		}
		//5 如果没有登录就返回未登录的结果，通过输出流的方式向客户端页面响应时间
		httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
		log.info("不放行 ，写数据进去");
	}

	@Override
	public void destroy() {
		Filter.super.destroy();
	}

	public static boolean check(String[] urls ,String requestURI){
		for (String url : urls) {
			boolean match = PATH_MATCHER.match(url, requestURI);
			if(match){
				log.info("直接放行");
				return true;
			}
		}
		log.info("拦截请求返回 false");
		return false;
	}
}
